-- NatShell工具模块

local type, next, pairs, ipairs, loadfile, table, string
    = type, next, pairs, ipairs, loadfile, table, string

local tonumber, tostring, math = tonumber, tostring, math

local require = require

local nxo = require "nixio"
local nfs = require "nixio.fs"
local ipc = require "luci.ip"
local sys = require "luci.sys"
local utl = require "luci.util"
local dsp = require "luci.dispatcher"
local uci = require "luci.model.uci"
local lng = require "luci.i18n"
local tml = require "luci.template"
local http = require "luci.http"
require "luci.cbi"
module "luci.model.nac_nsutil"


-- 错误渲染
function error_render(m, rt_code, data)
    m.render= function ( ... )
        tml.render("nac/error", {title=m.title,rt_code=rt_code, message=data})
    end

end

-- 格式化在线时长
function format_life(life_info)
    local life = tonumber(life_info)
    run_days=math.modf(life / 86400 )
    run_hour=math.modf((life % 86400)/3600)
    run_minute= math.modf((life % 3600)/60)
    run_second=life % 60
  return (run_days > 0 and run_days .."d " or "")..(run_hour > 0 and run_hour.."h " or "")..(run_minute > 0 and run_minute.."min " or "")..run_second.."sec"
end

-- 转换流量单位
function format_traffic( bytes )
    local flow = tonumber(bytes)
    if (flow == 0) then
         return '0 B'
    end
    local unit = 1024
    sizes = {'B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'}
    i = math.floor(math.log(flow) / math.log(unit))
    flow = (flow / math.pow(unit, i)) 
    return string.format("%.2f %s", flow,sizes[i+1]) 
    --return flow
end

-- 速率转换
function format_rate( bytes )
    local flow = tonumber(bytes)
    if (flow == 0) then
         return '0 B/s'
    end
    local unit = 1024
    sizes = {'B/s','KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'}
    i = math.floor(math.log(flow) / math.log(unit))
    flow = (flow / math.pow(unit, i)) 
    return string.format("%.2f %s", flow,sizes[i+1]) 
    --return flow
end
